<template>
  <el-dialog :visible.sync="isShow"
    destroy-on-close
    title="角色编辑"
    width="400px"
    top="60px"
    :close-on-click-modal="false">
    <el-form ref="form" :model="fields" :rules="rules" label-width="80px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model.trim="fields.name" autocomplete="off" size="small" placeholder="请输入角色名称" maxlength="64" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model.trim="fields.description" autocomplete="off" size="small" placeholder="请输入角色描述" maxlength="128" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="loading" size="mini" @click="closePage"
        >取消</el-button
      >
       <el-button
        :loading="loading"
        type="primary"
        size="mini"
        @click="onOkBtnClick"
        >保存</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { saveOrUpdate, get } from '@/api/role'
export default {
  props: {
    value: {
      type: Object,
      default: () => Object.create({})
    }
  },
  data() {
    return {
      isShow: true,
      fields: {},
      parents: [],
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      }
    }
  },
  watch: {
    'isShow': function() {
      this.$emit('input', null)
    }
  },
  created() {
    this.get(this.value.id || null)
  },
  methods: {
    onOkBtnClick() {
      this.submitForm()
    },
    submitForm() {
      this.$refs['form'].validate((valid) => {
        valid && saveOrUpdate(this.fields).then(() => {
          this.isShow = false
          this.$parent.onSearchBtnClick()
        }).catch(() => { })
      })
    },
    resetForm() {
      this.$refs['form'].resetFields()
    },
    async get(id) {
      const res = await get(id)
      if (!res.type) {
        res.type = 'menu'
      }
      this.fields = res
      this.parents = [{ name: '一级资源', id: '0' }].concat(res.resouces || [])
      if (!this.fields.pid && this.parents.length) {
        this.fields.pid = this.parents[0].id
      }
    },
    closePage() {
      this.isShow = false
      this.resetForm()
    },
  }
}
</script>
